/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */
import {AsyncStorage} from 'react-native'

let angryMood = require('../image/tx4.jpg');
let peaceMood = require('../image/tx2.jpg');
let happyMood = require('../image/tx.jpg');
let sadMood = require('../image/tx5.jpg');
let miseryMood = require('../image/tx3.jpg');

export default class DataHandler {

    static realDiaryList = [];
    static listIndex = 0;

    static getAllTheDiary() {
        return new Promise(
            function (resolve, reject) {
                AsyncStorage.getAllKeys().then(
                    (Keys) => {
                        if (Keys.length === 0) {
                            // let returnValue = {
                            //     diaryTime: '没有历史记录',
                            //     diaryTitle: '没有历史记录',
                            //     diaryBody: ''
                            // };
                            resolve(DataHandler.realDiaryList);
                            return;
                        }
                        AsyncStorage.multiGet(Keys).then(
                            (results) => {
                                let resultsLength = results.length;
                                for (let counter = 0; counter < resultsLength; counter++) {
                                    DataHandler.realDiaryList[counter] = JSON.parse(results[counter][1]);
                                    switch (DataHandler.realDiaryList[counter].mood) {
                                        case 2:
                                            DataHandler.realDiaryList[counter].mood = angryMood;
                                            break;
                                        case 3:
                                            DataHandler.realDiaryList[counter].mood = sadMood;
                                            break;
                                        case 4:
                                            DataHandler.realDiaryList[counter].mood = happyMood;
                                            break;
                                        case 5:
                                            DataHandler.realDiaryList[counter].mood = miseryMood;
                                            break;
                                        default:
                                            DataHandler.realDiaryList[counter].mood = peaceMood;
                                    }
                                    let atime = new Date(DataHandler.realDiaryList[counter].time);
                                    DataHandler.realDiaryList[counter].time = '' + atime.getFullYear() + '年' + (atime.getMonth() + 1) + '月' + atime.getDate() + '日 星期' + (atime.getDay() + 1) + ' ' + atime.getHours() + ':' + atime.getMinutes();
                                    DataHandler.bubleSortDiaryList();
                                    resolve(DataHandler.realDiaryList);

                                }
                            }
                        );
                    }
                ).catch(
                    (error) => {
                        console.log('A error happens while read all the diary.');
                        console.log(error);
                        AsyncStorage.clear();
                        resolve(DataHandler.realDiaryList);
                    }
                )
            }
        );
    }

    //使用冒泡排序对日记列表进行排序
    static bubleSortDiaryList() {
        let tempObj;
        for (let i = 0; i < DataHandler.realDiaryList.length; i++) {
            for (let j = 0; j < DataHandler.realDiaryList.length - i - 1; j++) {
                if (DataHandler.realDiaryList[j].index > DataHandler.realDiaryList[j + 1].index) {
                    tempObj = DataHandler.realDiaryList[j];
                    DataHandler.realDiaryList[j] = DataHandler.realDiaryList[j + 1];
                    DataHandler.realDiaryList[j + 1] = tempObj;
                }
            }
        }
    }

    //请求上一篇日记数据的处理函数
    static getPreviousDiary() {
        if (DataHandler.listIndex < 1) return null;
        DataHandler.listIndex--;
        return {
            uiCode: 2,
            diaryTime: DataHandler.realDiaryList[DataHandler.listIndex].time,
            diaryTitle: DataHandler.realDiaryList[DataHandler.listIndex].title,
            diaryMood: DataHandler.realDiaryList[DataHandler.listIndex].mood,
            diaryBody: DataHandler.realDiaryList[DataHandler.listIndex].body
        };
    }

    static getDiaryAtIndex(aIndex) {
        DataHandler.listIndex = aIndex;
        return {
            uiCode: 2,
            diaryTime: DataHandler.realDiaryList[DataHandler.listIndex].time,
            diaryTitle: DataHandler.realDiaryList[DataHandler.listIndex].title,
            diaryMood: DataHandler.realDiaryList[DataHandler.listIndex].mood,
            diaryBody: DataHandler.realDiaryList[DataHandler.listIndex].body
        };
    }

    //请求下一篇日记数据的处理函数
    static getNextDiary() {
        if (DataHandler.listIndex >= (DataHandler.realDiaryList.length - 1)) return null;
        DataHandler.listIndex++;
        return {
            uiCode: 2,
            diaryTime: DataHandler.realDiaryList[DataHandler.listIndex].time,
            diaryTitle: DataHandler.realDiaryList[DataHandler.listIndex].title,
            diaryMood: DataHandler.realDiaryList[DataHandler.listIndex].mood,
            diaryBody: DataHandler.realDiaryList[DataHandler.listIndex].body
        };
    }

    //保存日记数据
    static saveDiary(newDiaryMood, newDiaryBody, newDiaryTitle) {
        return new Promise(function (resolve, reject) {
            let currentTime = new Date();
            let timeString = '' + currentTime.getFullYear() + '年' + (currentTime.getMonth() + 1) + '月' + currentTime.getDate() + '日 星期' + (currentTime.getDay() + 1) + ' ' + currentTime.getHours() + ':' + currentTime.getMinutes();

            let aDiary = Object();
            aDiary.title = newDiaryTitle;
            aDiary.body = newDiaryBody;
            aDiary.mood = newDiaryMood;
            aDiary.time = currentTime;
            aDiary.sectionID = '' + currentTime.getFullYear() + '年' + (currentTime.getMonth() + 1) + '月';
            aDiary.index = Date.parse(currentTime);
            //从当前时间生成唯一值，用来索引日记列表，这个值精确到毫秒，可以认为它是唯一的
            AsyncStorage.setItem('' + aDiary.index, JSON.stringify(aDiary)).then(
                () => {
                    let totalLength = DataHandler.realDiaryList.length;
                    DataHandler.realDiaryList[totalLength] = aDiary;
                    DataHandler.listIndex = totalLength;
                    let newMoodIcon;
                    switch (newDiaryMood) {
                        case 2:
                            newMoodIcon = angryMood;
                            return;
                        case 3:
                            newMoodIcon = sadMood;
                            return;
                        case 4:
                            newMoodIcon = happyMood;
                            return;
                        case 5:
                            newMoodIcon = peaceMood;
                            return;
                        default:
                            newMoodIcon = peaceMood;
                    }
                    DataHandler.realDiaryList[totalLength].mood = newMoodIcon;
                    let aValue = {
                        diaryList: DataHandler.realDiaryList,
                        uiCode: 1
                    };
                    resolve(aValue);//返回最新写日记数据
                }
            ).catch(
                (error) => {
                    console.log('Saving failed, error:' + error.message);
                }
            );
        });
    }

}



